var ctx;

var unitName = "";
var regionId;
var buildingId;
var pSize;

function setCtx(ctx){
	this.ctx = ctx;
	initListener();
}

/**
 * 选择小区 调用小区相应的区域信息
 */
function initListener(){

	$("#cellid").change(function (){
		cellId = $("#cellid").val();
		if(cellId != ""){
			$.ajax({
		        type : "GET",
		        url : ctx + "/cellUnit/getRegionByCellId",
		        cache : false,
		        dataType : 'json',
		        data : {
		        	cellid : cellId,
		        },
		        success : function(data) {
		        	if (data.success) {
		                var result = "<option value='" + "'>全部</option>";
		                $.each(data.obj, function(index, item) {
		                	if(item.id == regionId){
		                		result += "<option id='" + item.id + "'"+" selected='selected'" + " value='" + item.id + "'>" + item.name + "</option>";
		                	}else{
		                		result += "<option id='" + item.id + "'" + " value='" + item.id + "'>" + item.name + "</option>";
		                	}
		                });
		                $("#regionid").html("");
		                $("#regionid").append(result);
		                $("#regionid").change();
		            }
		        }
			});
		} else {
			var result = "<option value='" + "'>全部</option>";
			$("#regionid").html("");
            $("#regionid").append(result);
            $("#regionid").change();
            
			$("#buildingid").html("");
            $("#buildingid").append(result);
            $('#buildingid').change();
		}
		
	});
	/**
	 * 根据区域id 查询相应区域下所以的楼栋信息
	 */
	$("#regionid").change(function(){
		regionId = $('#regionid').val();
    	if (regionId != ""){
    		$.ajax({
		        type : "GET",
		        url : ctx + "/cellUnit/getBuildingByRegionId",
		        cache : false,
		        dataType : 'json',
		        data : {
		        	regionid : regionId,
		        },
		        success : function(data) {
		        	if (data.success) {
		        		var result = "<option value='" + "'>全部</option>";
		                $.each(data.obj, function(index, item) {
		                	if(item.id == buildingId){
		                		result += "<option id='" + item.id + "'" +" selected='selected'" + " value='" + item.id + "'>" + item.buildingName + "</option>";
		                	}else{
		                		result += "<option id='" + item.id + "'" + " value='" + item.id + "'>" + item.buildingName + "</option>";
		                	}
		                });
		                $("#buildingid").html("");
		                $("#buildingid").append(result);
		                $('#buildingid').change();
		            }
		        }
			});
    	} else {
    		var result = "<option value='" + "'>全部</option>";
			$("#buildingid").html("");
            $("#buildingid").append(result);
            $('#buildingid').change();
    	}
	});
	
	$('#buildingid').change(function() {
		buildingId = $('#buildingid').val();
    });
	
}
function gotoPage(page){
	unitName = ifNull($("#unitname").val());
	regionId = ifNull($("#regionid").val());
	buildingId = ifNull($("#buildingid").val());
	pSize = ifNull($("#pSize").val());
	//解决ie9以下placeholder与value重复的问题
	if(unitName == $("#unitname").attr("placeholder")){
		unitName = "";
	}
	
	loadContent("/cellUnit/cellUnitList?pNo="+ page +"&unitName="+ unitname+ "&regionId="+ regionId+ "&buildingId="+ buildingId + "&pSize="+ pSize);
}

function gotoCellUnitPage(page) {
	if(page == null){
		page = $(".inputclass").val();
	}
	unitName = ifNull($("#unitname").val());
	regionId = ifNull($("#regionid").val());
	buildingId = ifNull($("#buildingid").val());
	pSize = ifNull($("#pSize").val());
	//解决ie9以下placeholder与value重复的问题
	if(unitName == $("#unitname").attr("placeholder")){
		unitName = "";
	}
	
	loadContent("/cellUnit/cellUnitList?pNo="+ page +"&unitName="+ unitName
	+ "&regionId="+ regionId+ "&buildingId="+ buildingId + "&pSize="+ pSize);
}

function ifNull(mess){
	if(mess == null || mess == undefined){
		mess = "";
	}
	
	return mess;
}

//条件搜索菜单列表
function getCellUnitList(){
	unitName = ifNull($("#unitname").val());
	regionId = ifNull($("#regionid").val());
	buildingId = ifNull($("#buildingid").val());
	pSize = ifNull($("#pSize").val());
	//解决ie9以下placeholder与value重复的问题
	if(unitName == $("#unitname").attr("placeholder")){
		unitName = "";
	}
	
	loadContent("/cellUnit/cellUnitList?pNo=1&unitName="+ unitName
	+ "&regionId="+ regionId+ "&buildingId="+ buildingId + "&pSize="+ pSize);
	
}
/**
 * 小区详情
 */
function detailCellunit(id){
	loadContent("/cellUnit/cellUnitdetail?id="+id+"");
}

//新增或编辑用户(1:新增 2:编辑)
function saveOrUpdateCellunit(id) {
	if(id != null){
		msg = "编辑单元信息";
		url =  ctx + "/cellUnit/editcellUnit?id="+id+"";
		saveOrUpdateBox(msg,url,2);
		
	}else{
		msg = "新增单元信息";
		url =  ctx + "/cellUnit/editcellUnit?id=0";
		saveOrUpdateBox(msg,url,1);
	}
	
}

var index;
function saveOrUpdateBox(msg,url,state){
  //官网欢迎页
   index = layer.open({
      type: 2,
      //skin: 'layui-layer-lan',
      title: msg,
      fix: false,
      shadeClose: true,
      scrollbar: false,
      maxmin: false,
      edit: true,
      closeBtn: 1,
      area: ['500px', '317px'],
      content: url,
      btn: ['确定', '取消']
	    ,yes: function(index, layero){ //或者使用btn1
	        //按钮【按钮一】的回调
	    	var iframeWin = window[layero.find('iframe')[0]['name']]; 
	    	iframeWin.saveOrUpdateCellUnit(state);

	    },cancel: function(index){ //或者使用btn2
	        //按钮【按钮二】的回调
	    }
	    });
}

//鼠标滑入一行改变背景颜色
function mouseoverOne(target){
	 $(target).children().each(function(){
		  	    $(this).css("background","#D3F0F1");
		     });
}

//鼠标滑出一行恢复原来的背景颜色
function mouseoutOne(target){
	 $(target).children().each(function(){
	  	    $(this).css("background","");
	     });
}
//选择或取消选中当前记录，同时改变背景颜色
function selectOne(id,target){
    if(target.checked){    
        $("#btn" + id).attr("checked", true); 
       $(target).parents("tr").children().each(function(){
    	    $(this).css("background","#D3F0F1");
       });
       
    }else{    
        $("#btn" + id).attr("checked", false); 
        $(target).parents("tr").children().each(function(){
    	    $(this).css("background","");
       });
    } 
}


function deleteByIds(){
	if($("img[name='buildingChecked'][src*=honggou]").length == 0){
		layer.msg("请选择要删除的记录!",{
			icon: 3,
			time: 2000 //2秒关闭（如果不配置，默认是3秒）
		});
	}else{
		var delIds = [];
		    $("#tableTbody img[name='buildingChecked'][src*=honggou]").each(function(){ 
		    	delIds.push($(this).attr("class")); 
		    }); 
		    var vals = delIds.join(',');//转换为逗号隔开的字符串 
			layer.confirm('确认删除?', {icon: 3, title:'提示'}, function(index){
			    //do something
				$.post(ctx+"/cellUnit/deleteCellunit",{
					ids:vals
				},function(data){
					data = JSON.parse(data);
					if(data.success){
						layer.msg("删除成功",{
							icon: 1,
							time: 2000 //2秒关闭（如果不配置，默认是3秒）
						},function(){
							layer.close(index);
							loadContent("/cellUnit/cellUnitList");
						});
					} else {
						layer.msg(data.msg,{
							icon: 2,
							time: 2000 //2秒关闭（如果不配置，默认是3秒）
						});
					}
				});
			    layer.close(index);
			});

		
	}
}

function updateSort(cellUnitId){
	if(cellUnitId != null){
   		$.get(ctx + "/cellUnit/updateSort",{
			id: cellUnitId
   		},function(data){
        data = JSON.parse(data);
		if(data.success){
			layer.msg("操作成功",{
			    icon: 1,
			    time: 2000 //2秒关闭（如果不配置，默认是3秒）
			},function(){
				loadContent("/cellUnit/cellUnitList");
			});
		}else{
			layer.msg(data.msg,{
			    icon: 2,
			    time: 2000 //2秒关闭（如果不配置，默认是3秒）
			});
		}
	});
	}
}
